package com.qianniu.napi.common.shiro;

import com.alibaba.fastjson.JSON;
import com.google.common.base.Strings;
import com.qianniu.napi.admin.entity.MerchantApp;
import com.qianniu.napi.common.config.Constants;
import com.qianniu.napi.common.util.AesUtil;
import com.qianniu.napi.common.util.EhcacheUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

public class TokenFilter extends AccessControlFilter {

    private static final Logger log = LoggerFactory.getLogger(TokenFilter.class);

    public TokenFilter() {
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {

//        Subject subject = getSubject(request, response);
//        if (subject == null) {
//            // 没有登录
//            return false;
//        }
        HttpServletRequest req = (HttpServletRequest) request;
        log.info("========preHandle come");
        log.info("========url=" + req.getRequestURI());
        log.info("========QueryString=" + req.getQueryString());
        log.info("========");
        Session session = SecurityUtils.getSubject().getSession();
        if (request.getParameter("t") == null) return false;
        String token = java.net.URLDecoder.decode(request.getParameter("t"), "UTF-8");
        log.debug(">>>token=" + token);
        MerchantApp merchant = getMerchantByToken(token);

        session.setAttribute("uid", merchant.getUid());
        session.setAttribute("mid", merchant.getMid());
        session.setAttribute("appid", merchant.getAppid());
        session.setAttribute("mpid", merchant.getId());
        session.setAttribute("appType", merchant.getAppType());
        session.setAttribute("sid", merchant.getSid());
        session.setAttribute("subsid", merchant.getSubsid());
        session.setAttribute("mainmpid", merchant.getMainmpid());

        return true;
    }

    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) throws Exception {
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        return true;
    }

    private MerchantApp getMerchantByToken(String token) {
        log.info(">>>>>>>>>>>>>>>getMerchantByToken start and token=" + token);

        if (Strings.isNullOrEmpty(token)) return null;
        MerchantApp mapp = new MerchantApp();

//        RedissonClient redis = (RedissonClient) SpringUtil.getBean("redisClient");

//        RedissonClient redis = new RedissonConfig().getRedisson();
//        log.info(">>>getMerchantByToken redis="+JSON.toJSONString(redis));
        //部分关键代码
//        EhcacheUtil.getInstance().put(Constants.EHCACHE_KEY,"test","123456");
//        String dd = (String) EhcacheUtil.getInstance().get(Constants.EHCACHE_KEY,"test");
//        log.info("======>>>>>>>dd="+dd);

//        EhcacheUtil.getInstance().put(Constants.EHCACHE_KEY,token,"123456");
        String key = (String) EhcacheUtil.getInstance().get(Constants.EHCACHE_KEY, token);
        log.info("======>>>>>>>key=" + key);

        String data = Strings.isNullOrEmpty(key) ? AesUtil.decrypt(token, Constants.ENCODE_KEY) : key;

        log.info(">>>getMerchantByToken key=" + data);

        if (Strings.isNullOrEmpty(key)) EhcacheUtil.getInstance().put(Constants.EHCACHE_KEY, token, data);

        log.info(">>>data=" + data);
        String[] mainvals = data.split("##");
        log.debug("=====================================mainvals.size=");
        log.debug("=====================================mainvals.size="+mainvals.length);
        String[] vals = mainvals[0].split("__");
        try {
            if (mainvals.length >= 2) mapp.setMainmpid(Long.valueOf(mainvals[1]));
        } catch (Exception e) {
            log.error("mapp.setMainmpid error for mainvals[1]=" + mainvals[1]);
        }

        if (vals.length <= 3) return mapp;

        //mid+mpid+[uid]+random+appid+apptype+sid
        mapp.setMid(Long.valueOf(vals[0]));
        mapp.setId(Long.valueOf(vals[1]));
        if (!Strings.isNullOrEmpty(vals[2])) mapp.setUid(Long.valueOf(vals[2]));
        if (vals.length >= 5) {
            mapp.setAppid(vals[4]);
        }
        if (vals.length >= 6) {
            mapp.setAppType(Integer.valueOf(vals[5]));
        }
        if (vals.length >= 7) {
            mapp.setSid(Long.valueOf(vals[6]));
        }
        log.info(">>>merchant=" + JSON.toJSONString(mapp));
        return mapp;
    }
}
